<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import resize from './mixins/resize'
import {salecount} from "@/api/commodity/commodity";

const animationDuration = 3000

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.showsalecount()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    showsalecount() {
      let showsalecount = echarts.init(this.$el, 'macarons');
      salecount().then(response => {
        let array = response.data;
        array.sort((a, b) => b.count - a.count);

        // 只统计前10个数据项
        let top10Array = array.slice(0, 10);

        let cnames = top10Array.map(item => item.cname);
        let counts = top10Array.map(item => item.count);

        let seriesData = cnames.map((name, index) => {
          return {name: name, value: counts[index]};
        });

        showsalecount.setOption({
          title: {
            text: '前10位商品销售量统计',
            left: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: function(params) {
              return `${params.name}: 销量 ${params.value}`;
            }
          },
          toolbox: {
            feature: {
              dataView: {show: true, readOnly: false},
              restore: {show: true},
              saveAsImage: {show: true}
            }
          },
          legend: {
            left: 'center',
            bottom: '10',
            type: 'scroll',
            max: 5,
            data: cnames
          },
          series: [
            {
              name: '产品销售量',
              type: 'pie',
              radius: ['25%', '70%'], // 内外半径
              center: ['50%', '50%'], // 中心点位置
              roseType: 'area',
              data: seriesData,
              animationEasing: 'cubicInOut',
              animationDuration: 2600,
              itemStyle: {
                borderRadius: 4
              }
            }
          ]
        });
      });
    }
  }
}
</script>
